<template>
    <div ref="chartRef" class="trend-chart"></div>
</template>

<script setup>
import { ref, watch, onMounted, defineProps } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
    chartData: {
        type: Object,
        required: true
    },
    chartType: {
        type: String,
        required: true
    }
});

const chartRef = ref(null);
let chartInstance = null;

const chartTitles = {
    users: '用户增长趋势',
    activities: '活跃度趋势',
    revenue: '收入预测趋势'
};

const getChartOptions = () => {
    return {
        title: {
            text: chartTitles[props.chartType] || '趋势分析',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['历史数据', '预测数据'],
            bottom: 0,
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: [...props.chartData.labels, '七月', '八月', '九月'] // Extend labels for forecast
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '历史数据',
                type: 'line',
                data: props.chartData.data,
                smooth: true,
            },
            {
                name: '预测数据',
                type: 'line',
                data: new Array(props.chartData.data.length).fill(null).concat(props.chartData.forecast),
                smooth: true,
                lineStyle: {
                    type: 'dashed'
                }
            }
        ]
    };
};

const renderChart = () => {
    if (chartInstance) {
        chartInstance.setOption(getChartOptions());
    }
};

onMounted(() => {
    if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value);
        renderChart();
        window.addEventListener('resize', () => chartInstance.resize());
    }
});

watch(() => [props.chartData, props.chartType], () => {
    renderChart();
}, { deep: true });

</script>

<style scoped>
.trend-chart {
    width: 100%;
    height: 400px;
}
</style>